package com.dgw.elasticsearch.controller;

import com.dgw.elasticsearch.entity.Admin;
import com.dgw.elasticsearch.entity.Article;
import com.dgw.elasticsearch.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @program: springboot-elasticsearch
 * @description:
 * @author: Mr.Dai
 * @create: 2020-02-29 10:50
 **/
@RestController
public class AdminController {

    @Autowired
    private AdminRepository adminRepository;

    // http://localhost:8080/saveOrUpdate

    /**
     *  send data
     * {
     * 	"username":"dgw3",
     * 	"password":"root",
     * 	"loveThings":"postman(二):使用postman发送get or post请"
     * }
     */
    @PostMapping("saveOrUpdate")
    public String saveOrUpdate(@RequestBody Admin admin){
        if(admin.getId()==null){
            admin.setId(System.currentTimeMillis());
        }
        adminRepository.save(admin);
        return "保存成功";
    }
    //http://localhost:8080/delete?id=1582946734759
    @GetMapping("delete")
    public String delete(Long id){
        try {
            adminRepository.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败";
        }
        return "删除成功";
    }
    //http://localhost:8080/findById?id=1582946734759
    @GetMapping("findById")
    public Admin findById(long id){
        Optional<Admin> admin = adminRepository.findById(id);
        if(admin.isPresent()){
            return admin.get();
        }else{
            return null;
        }
    }
    //http://localhost:8080/findAll
    @GetMapping("findAll")
    public Iterable<Admin> findAll(){
            return adminRepository.findAll();
    }
}
